var express = require('express')
var router = express.Router()

const { getList, getDetail, postNew, postUpdate, postDelete } = require('../controller/index')
const { Success, Error } = require('../model/res')
const loginCheck = require('../middleware/loginCheck')

/* GET home page. */
router.get('/list', async (req, res, next) => {
    let author = req.query.author || ''
    let keyword = req.query.keyword || ''
    let data = await getList(author, keyword)
    res.json(new Success(data))
})

router.get('/detail', async (req, res, next) => {
    let id = req.query.id
    let data = await getDetail(id)
    // 参数正确
    if (id) return res.json(new Success(data))
    // 参数错误
    res.json(new Error('请求文章内容失败'))
})

/* POST home page. */
router.post('/new', loginCheck, async (req, res, next) => {
    req.body.author = req.session.username // 临时数据
    let data = await postNew(req.body)
    // 参数正确
    if (data) return res.json(new Success(data))
    // 参数错误
    res.json(new Error('添加文章失败'))
})

router.put('/update', loginCheck, async (req, res, next) => {
    let id = req.query.id
    let data = await postUpdate(id, req.body)
    // 参数正确
    if (data) return res.json(new Success(data))
    // 参数错误
    res.json(new Error('更新文章失败'))
})
/* DELETE home page. */
router.delete('/delete', loginCheck, async (req, res, next) => {
    let id = req.query.id
    let data = await postDelete(id, req.session.username)
    // 参数正确
    if (data) return res.json(new Success(data))
    // 参数错误
    res.json(new Error('删除文章失败'))
})

module.exports = router
